const Router = require('koa-router');
const db = require('../database/config/db');
const tableName = 'goods';

const router = new Router();

// 查询符合搜索参数的商品列表
router.get('/getGoodsListBySearch', async ctx => {
    try {
        // 关键词 页数 条件 是否降序
        let {name, page, mark, isdesc} = ctx.request.query;
        // mark: all, sales, price, comment
        let where = `WHERE NAME LIKE '%${name}%'`;
        let order = ``;
        let sort = isdesc === 'true' ? 'DESC' : 'ASC'
        switch (mark) {
            case 'all':
                where += ''
                break;
            case 'sales':
                order += `ORDER BY SALES_COUNT ${sort}`;
                break;
            case 'price':
                order += `ORDER BY PRESENT_PRICE ${sort}`;
                break;
            case 'new':
                order += `ORDER BY UPDATE_TIME DESC`;
                break;
            default:
                break;
        }
        let num = 10; // 每页显示数量
        let start = (page - 1) * num; // 开始位置
        let query = `SELECT * FROM ${tableName} ${where} ${order} LIMIT ${start}, ${num}`;
        console.log(query);
        let result = await db.QUERY_All(query);
        ctx.body = {
            code: 200,
            message: "请求成功",
            data: result
        }
    } catch (err) {
        ctx.body = {
            code: 500,
            message: err
        }
    }
})

// ====================


module.exports = router;